# 观察者模式

# ⭐=> 一种一对多的依赖关系，让多个观察者对象同时监听某一个主题对象。

# 角色
# 主题: 被观察的对象，当主题状态发生变化时，会通知所有的观察者对象
# 观察者: 观察主题对象的状态变化，当主题对象的状态发生变化时，观察者对象会收到通知并更新自己的状态
# 具体主题: 实现主题接口，定义主题的具体实现
# 具体观察者: 实现观察者接口，定义观察者的具体实现

from abc import ABCMeta, abstractmethod
class Observer(metaclass=ABCMeta):
    @abstractmethod
    def update(self, message):
        pass

class Subject(metaclass=ABCMeta):
    @abstractmethod
    def attach(self, observer):
        pass

    @abstractmethod
    def detach(self, observer):
        pass

    @abstractmethod
    def notify(self):
        pass

class ConcreteObserver(Observer):
    def __init__(self, name):
        self.name = name

    def update(self, message):
        print(self.name + " received message: " + message)

class ConcreteSubject(Subject):
    def __init__(self):
        self.observers = []

    def attach(self, observer):
        self.observers.append(observer)

    def detach(self, observer):
        self.observers.remove(observer)

    def notify(self):
        for observer in self.observers:
            observer.update("Hello, observer")

if __name__ == "__main__":
    subject = ConcreteSubject()
    observer1 = ConcreteObserver("Observer 1")
    observer2 = ConcreteObserver("Observer 2")
    subject.attach(observer1)
    subject.attach(observer2)
    subject.notify()
    subject.detach(observer1)
    subject.notify()
    # Output: Observer 1 received message: Hello, observer Observer 2 received message: Hello, observer Observer 1 received message: Hello, observer